//
//  BankCardNetService.m
//  HPZZTong
//
//  Created by wenjun on 14-5-9.
//  Copyright (c) 2014年 Handpay. All rights reserved.
//

#import "BankCardNetService.h"
#import "HPClientEngine.h"

typedef void (^RequestComplete)(NSString * response);

@implementation BankCardNetService

+ (void)doGetBankCardList:(void (^)(NSDictionary *))complete
{
    NSString * swiperFactor = [SwiperService resetFactor];
    NSString * nowTimeS = [swiperFactor substringToIndex:(swiperFactor.length -2)];
    NSString * mac = [[NSMutableString alloc] initWithFormat:@"%@ %@", nowTimeS, SwiperService.csn];
    [SwiperService doMac:mac complete:^(HPSwiperResult *swiperResult) {
        [self queryCardList:nowTimeS mac:swiperResult.value serviceInfo:PREV_QUERY_BANKCARD complete:^(NSDictionary *resultDic) {
            dispatch_async(dispatch_get_main_queue(), ^{
                complete(resultDic);
            });
        }];
    }];
}

+ (void)queryCardList:(NSString*)time mac:(NSString *)mac serviceInfo:(NSString*)serviceInfo complete:(void (^)(NSDictionary *))complete
{
    NSString * postParam = [self postParamWithTime:time mac:mac serviceInfo:serviceInfo];
    [self sendRequestWithParam:postParam complete:^(NSString *response) {
        complete([self parseBankCardListResult:response]);
    }];
}

+ (NSString *)postParamWithTime:(NSString *)time mac:(NSString *)mac serviceInfo:(NSString *)serviceInfo
{
    NSString* xmlFormat = @"<?xml version=\"1.0\" encoding=\"utf-8\"?><cupMobile application=\"UPCards\" version=\"1.01\"><transaction type=\"BillEnquiry.APReq\"><submitTime>%@</submitTime><cardSerialNumber>%@</cardSerialNumber><serviceInfo>%@</serviceInfo><SpId>%s</SpId></transaction><securityChipTp>%s</securityChipTp><mac>%@</mac></cupMobile>";
    return [NSString stringWithFormat:xmlFormat, time, SwiperService.csn, serviceInfo, SPID, CHIPTP, mac];
}

+ (NSDictionary *)parseBankCardListResult:(NSString *)response
{
    NSString * serviceInfo = [self getRange:response prev:@"<serviceInfo>" last:@"</serviceInfo>"];
    NSString * responseCode = [self getRange:response prev:@"<responseCode>" last:@"</responseCode>"];
    if (responseCode.length == 0)
    {
        responseCode = @"01";
    }
    NSMutableArray* accountArray = [[NSMutableArray alloc] init];
    if ([serviceInfo hasPrefix:PREV_QUERY_BANKCARD] && [responseCode isEqualToString:SUCCESS_CUP])
    {
        NSUInteger index = [PREV_QUERY_BANKCARD length];
        int count = [[serviceInfo substringWithRange:NSMakeRange(index, 2)] intValue];
        index += 2;
        const int accountLen = 20;
        
        for (int i = 0; i < count; i++)
        {
            if (index + accountLen > [serviceInfo length])
            {
                break;
            }
            NSRange accountRange = NSMakeRange(index, accountLen);
            NSString* account = [serviceInfo substringWithRange:accountRange];
            account = [account stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            [accountArray addObject:account];
            index += accountLen;
        }
    }
    NSMutableDictionary* dic = [NSMutableDictionary dictionary];
    [dic setObject:responseCode forKey:@"responseCode"];
    [dic setObject:accountArray forKey:@"cardList"];
    return dic;
}

+ (NSString*)getRange:(NSString*)src prev:(NSString*)prev last:(NSString*)last{
	if (!src || !prev || !last) {
        return nil;
    }
    
    NSRange prevRange = [src rangeOfString:prev];
    NSRange lastRange = [src rangeOfString:last];
    
    if (prevRange.length == 0 || lastRange.length == 0) {
        return nil;
    }
    
    NSUInteger targetLoc = prevRange.location + prevRange.length;
    NSUInteger targetLen = lastRange.location - targetLoc;
    NSRange targetRange = NSMakeRange(targetLoc, targetLen);
    return [src substringWithRange:targetRange];
}

+ (void)sendRequestWithParam:(NSString *)param complete:(RequestComplete)complete
{
    LOG(@"post:%@",param);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSMutableURLRequest * request = [[NSMutableURLRequest alloc] init];
        [request setURL:[NSURL URLWithString:[HPCLIENTENG getUrlByName:CUP_URL_NAME]]];
        NSMutableDictionary* headerDic = [NSMutableDictionary dictionaryWithDictionary:request.allHTTPHeaderFields];
        [headerDic setObject:@"text/xml" forKey:@"Content-type"];
        [request setAllHTTPHeaderFields:headerDic];
        [request setTimeoutInterval:60];
        [request setHTTPMethod:@"POST"];
        [request setHTTPBody:[param dataUsingEncoding:NSUTF8StringEncoding]];
        
        NSData * responseDate = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        LOG(@"response:%@",[[NSString alloc] initWithData:responseDate encoding:NSUTF8StringEncoding]);
        complete([[NSString alloc] initWithData:responseDate encoding:NSUTF8StringEncoding]);
    });
}


+ (void)doDeleteBankCard:(NSString *)account complete:(void (^)(NSDictionary *))complete
{
    NSString * swiperFactor = [SwiperService resetFactor];
    NSString * nowTimeS = [swiperFactor substringToIndex:(swiperFactor.length -2)];
    NSString * mac = [NSString stringWithFormat:@"%@ %@", nowTimeS, SwiperService.csn];
    [SwiperService doMac:mac complete:^(HPSwiperResult *swiperResult) {
        [self deleteCard:account time:nowTimeS mac:swiperResult.value complete:^(NSDictionary *resultDic) {
            dispatch_async(dispatch_get_main_queue(), ^{
                complete(resultDic);
            });
        }];
    }];
}

+ (void)deleteCard:(NSString *)account time:(NSString*)time mac:(NSString *)mac complete:(void (^)(NSDictionary *))complete
{
    NSString * serviceInfo = [NSString stringWithFormat:@"%@%@                    ", PREV_DELETE_BANKCARD, account];
    serviceInfo = [serviceInfo substringToIndex:24];
    NSString * postParam = [self postParamWithTime:time mac:mac serviceInfo:serviceInfo];
    [self sendRequestWithParam:postParam complete:^(NSString *response) {
        NSString * responseCode = [self getRange:response prev:@"<responseCode>" last:@"</responseCode>"];
        NSMutableDictionary * dic = [NSMutableDictionary dictionary];
        [dic setObject:responseCode forKey:@"responseCode"];
        complete(dic);
    }];
}


@end
